import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { Search as SearchIcon } from 'lucide-react';
import { supabase } from '../lib/supabase';
import type { Database } from '../lib/database.types';

type Poem = Database['public']['Tables']['poems']['Row'];

export function Search() {
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('all');
  const [results, setResults] = useState<Poem[]>([]);
  const [loading, setLoading] = useState(false);

  const categories = ['全部', '古诗', '词', '现代诗', '其他'];

  useEffect(() => {
    const searchPoems = async () => {
      if (!query.trim()) {
        setResults([]);
        return;
      }

      setLoading(true);
      try {
        let query = supabase
          .from('poems')
          .select('*')
          .or(`title.ilike.%${query}%,content.ilike.%${query}%`);

        if (category !== 'all') {
          query = query.eq('category', category);
        }

        const { data, error } = await query.limit(20);

        if (error) throw error;
        setResults(data || []);
      } catch (error) {
        console.error('Search error:', error);
        setResults([]);
      } finally {
        setLoading(false);
      }
    };

    const debounce = setTimeout(searchPoems, 300);
    return () => clearTimeout(debounce);
  }, [query, category]);

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white p-6 rounded-lg shadow-md mb-6">
        <div className="flex items-center space-x-4 mb-4">
          <div className="flex-1 relative">
            <input
              type="text"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="搜索诗词、作者..."
              className="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
            />
            <SearchIcon className="absolute left-3 top-2.5 h-5 w-5 text-gray-400" />
          </div>
          <select
            value={category}
            onChange={(e) => setCategory(e.target.value)}
            className="rounded-lg border border-gray-300 py-2 px-4 focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
          >
            {categories.map((cat) => (
              <option key={cat} value={cat === '全部' ? 'all' : cat}>
                {cat}
              </option>
            ))}
          </select>
        </div>
      </div>

      {loading ? (
        <div className="text-center py-12">
          <p className="text-gray-600">搜索中...</p>
        </div>
      ) : results.length > 0 ? (
        <div className="space-y-6">
          {results.map((poem) => (
            <Link
              key={poem.id}
              to={`/poem/${poem.id}`}
              className="block bg-white p-6 rounded-lg shadow-md hover:shadow-lg transition-shadow"
            >
              <h3 className="text-xl font-bold text-gray-900 mb-2">{poem.title}</h3>
              <p className="text-gray-600 mb-2">
                {poem.dynasty && `${poem.dynasty}代 · `}{poem.poet || '佚名'}
              </p>
              <p className="text-gray-800 line-clamp-2 font-serif">
                {poem.content}
              </p>
            </Link>
          ))}
        </div>
      ) : query ? (
        <div className="text-center py-12">
          <p className="text-gray-600">未找到相关诗词</p>
        </div>
      ) : null}
    </div>
  );
}